package com.cooba.game_fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.GameDetailsActivity;
import com.cooba.activitys.GameEvalDetailsActivity;
import com.cooba.activitys.VideoDetailsActivity;
import com.cooba.adapter.GameAdapter;
import com.cooba.adapter.GameEvaluationAdapter;
import com.cooba.application.MyApplication;
import com.cooba.bean.BannerBean;
import com.cooba.bean.GameBean;
import com.cooba.bean.GameEvaluationBean;
import com.cooba.bean.TuiJianBean;
import com.cooba.content_frament.BaseFragment;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.ACache;
import com.cooba.utils.CarURL;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.Constants;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.XGridView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by Administrator on 2015/12/29.
 * 游戏测评
 */
public class GameEvaluationFrament extends BaseFragment {
    private View view;
    private PullToRefreshListView rListView;
    private boolean isIncar;
    private boolean first_flag = true;
    private BannerBean banner;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String mac;
    private ACache acache;
    private GameEvaluationAdapter mAdapter;
    private String next_key = "0";
    private GameEvaluationBean gameevaluationbean;
    private int currentpage = 0;
    private boolean mIsFirstLoad=true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try {
            if (view == null) {
                view = initview(inflater);
            }
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.game_recommend_fragment, null, false);
        initPullTorefresh(view);
        initLoadViewHelper(rListView);
        acache = ACache.get(getContext());
        return view;
    }

    private void initPullTorefresh(View view) {
        rListView = (PullToRefreshListView) view.findViewById(R.id.lv_game);
        if (isIncar) {
            rListView.setPullRefreshEnabled(false);
        } else {
            rListView.setPullRefreshEnabled(true);
        }
        Log.d("wei","evaluation_init:"+isIncar);
        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
                if (first_flag) {
                    getFirstData();
                    //getBanner();
                } else {
                    getRefreshData();
                }
                String stringDate = CommonUtil.getStringDate();
                rListView.setLastUpdatedLabel(stringDate);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getMoreData();
            }
        });

        rListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String evalid;
//                if (banner != null && banner.getBannerList() != null && banner.getBannerList().size() > 0) {
//                    replyid = mAdapter.getList().get(position - 1).id;
//                } else {
//                    replyid = mAdapter.getList().get(position).id;
//                }
                evalid = mAdapter.getList().get(position).getId();
                Intent intent = new Intent(getActivity(), GameEvalDetailsActivity.class);
                intent.putExtra("eval_id", evalid);
                //intent.putExtra("dir_name", "recommend_app");
                startActivity(intent);
                // 放入已读列表
                saveToReadedList(view, evalid);
            }
        });
    }
    private void saveToReadedList(View view, String replyid) {
        acache.put("readed_eval_list_" + replyid, "true", SAVE_TIME);//保存一个月
        TextView tvTitle = (TextView) view.findViewById(R.id.tv_tittle);
        if (tvTitle != null) {
            tvTitle.setTextColor(getResources().getColor(R.color.darkgray));
        }
    }

    //获取顶部广告条
    private void getBanner() {
        String urlbanner;
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String now_time = sDateFormat.format(new java.util.Date());
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("now_time", now_time);
        params.addBodyParameter("tag", "evaluation_game");
        if (isIncar) {
            params.addBodyParameter("mac", mac);
            urlbanner =CarURL.bannerList;
        } else {
            urlbanner = ServerURL.httpUrl + ServerURL.bannerList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlbanner, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "游戏广告获取失败");
                String cacheData = acache.getAsString("evaluation_game_banner");
                if (cacheData != null) {
                    banner = new Gson().fromJson(cacheData, BannerBean.class);
                    if (banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                        initHeadView();
                    }
                } else {
                    getFirstData();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "游戏广告获取成功" + responseInfo.result);
                try {
                    banner = new Gson().fromJson(responseInfo.result, BannerBean.class);
                    if (banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                        initHeadView();
                        acache.put("evaluation_game_banner", responseInfo.result, SAVE_TIME);
                    } else {
                        getFirstData();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getFirstData() {
        if (mIsFirstLoad){
            helper.showLoading("正在加载...");
        }
        String urlgamelist;
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String user_id=SharedPreferencesUtil.getData(getContext(),"login_id","");
        params.addBodyParameter("user_id", user_id);
        params.addBodyParameter("next_key", "0");
        params.addBodyParameter("page_size", "10");
        if (isIncar) {
            urlgamelist = CarURL.gameEvaluationList;
        } else {
            urlgamelist = ServerURL.httpUrl + ServerURL.gameEvaluationList;
        }
        Log.d("wei","evaluation_first:"+isIncar);
        httpUtils.send(HttpRequest.HttpMethod.POST, urlgamelist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取游戏测评失败");
                String cacheData = acache.getAsString("evaluation_game_first");//从缓存中取数据
                Log.d("wei--", "读取:" + acache.getAsString("evaluation_game_first"));
                if (cacheData != null) {
                    first_flag = false;
                    gameevaluationbean = new Gson().fromJson(cacheData, GameEvaluationBean.class);
                    if (mAdapter == null) {
                        mAdapter = new GameEvaluationAdapter(getContext(), gameevaluationbean.getEvaluationList());
                        rListView.getRefreshableView().setAdapter(mAdapter);
                    } else {
                        mAdapter.setList(gameevaluationbean.getEvaluationList());
                    }
                    if (gameevaluationbean.getNext_key() == null) {
                        next_key = String.valueOf(gameevaluationbean.getEvaluationList().size() + Integer.parseInt(next_key));
                    } else {
                        next_key = gameevaluationbean.getNext_key();
                    }
                    if (gameevaluationbean.getEvaluationList().size()<10) {
                        rListView.setHasMoreData(false);
                    }
                } else {
                    Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取游戏测评成功" + responseInfo.result);
                try {
                    gameevaluationbean = new Gson().fromJson(responseInfo.result, GameEvaluationBean.class);
                    if (gameevaluationbean.getEvaluationList() != null&&gameevaluationbean.getEvaluationList().size()>0) {
                        if (mAdapter == null) {
                            mAdapter = new GameEvaluationAdapter(getContext(), gameevaluationbean.getEvaluationList());
                            rListView.getRefreshableView().setAdapter(mAdapter);
                        } else {
                            mAdapter.setList(gameevaluationbean.getEvaluationList());
                        }
                        if (gameevaluationbean.getNext_key() == null) {
                            next_key = String.valueOf(gameevaluationbean.getEvaluationList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gameevaluationbean.getNext_key();
                        }
                        acache.put("evaluation_game_first", responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        first_flag = false;
                        if (gameevaluationbean.getEvaluationList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                        mIsFirstLoad = false;
                        helper.restore();
                    }else {
                        helper.showEmpty("暂时没有数据", "重新加载",true, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                helper.restore();
                                getRefreshData();
                            }
                        });
                        //Toast.makeText(getContext(), "暂时没有新数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }

    private void getRefreshData() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        next_key="0";
        String user_id=SharedPreferencesUtil.getData(getContext(),"login_id","");
        params.addBodyParameter("user_id", user_id);
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urlgameevaluationlist;
        if (isIncar) {
            urlgameevaluationlist = CarURL.gameEvaluationList;
        } else {
            urlgameevaluationlist = ServerURL.httpUrl + ServerURL.gameEvaluationList;
        }
        Log.d("wei","evaluation_refresh:"+isIncar);
        httpUtils.send(HttpRequest.HttpMethod.POST, urlgameevaluationlist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取游戏测评失败");
                String cacheData = acache.getAsString("evaluation_game_refresh_" + next_key);//从缓存中取数据
                if (cacheData != null) {
                    gameevaluationbean = new Gson().fromJson(cacheData, GameEvaluationBean.class);
                    if (gameevaluationbean.getEvaluationList() != null&&gameevaluationbean.getEvaluationList().size()>0) {
                        mAdapter.addNewData(gameevaluationbean.getEvaluationList());
                        if (gameevaluationbean.getNext_key() == null) {
                            next_key = String.valueOf(gameevaluationbean.getEvaluationList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gameevaluationbean.getNext_key();
                        }
                        if (gameevaluationbean.getEvaluationList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    }
                } else {
                    Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                }

                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取游戏测评成功" + responseInfo.result);
                try {
                    gameevaluationbean = new Gson().fromJson(responseInfo.result, GameEvaluationBean.class);
                    if (gameevaluationbean.getEvaluationList() != null&&gameevaluationbean.getEvaluationList().size()>0) {
                        //mAdapter.addNewData(gameevaluationbean.getEvaluationList());
                        mAdapter.setList(gameevaluationbean.getEvaluationList());
                        if (gameevaluationbean.getNext_key() == null) {
                            next_key = String.valueOf(gameevaluationbean.getEvaluationList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gameevaluationbean.getNext_key();
                        }
                        acache.put("evaluation_game_refresh_" + next_key, responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        if (gameevaluationbean.getEvaluationList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    } else {
                        helper.showEmpty("暂时没有数据", "重新加载",true, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                helper.restore();
                                getRefreshData();
                            }
                        });
                        //Toast.makeText(getContext(), "暂时没有新数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }


    private void getMoreData() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String user_id=SharedPreferencesUtil.getData(getContext(),"login_id","");
        params.addBodyParameter("user_id", user_id);
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urlgameevaluationlist;
        if (isIncar) {
            urlgameevaluationlist = CarURL.gameEvaluationList;
        } else {
            urlgameevaluationlist = ServerURL.httpUrl + ServerURL.gameEvaluationList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlgameevaluationlist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取游戏测评失败");
                currentpage++;
                String cacheData = acache.getAsString("evaluation_game_load_more_" + currentpage);//从缓存中取数据
                Log.d("wei--", "加载游戏更多读取:" + acache.getAsString("evaluation_game_load_more_" + currentpage));
                if (cacheData != null) {
                    gameevaluationbean = new Gson().fromJson(cacheData, GameEvaluationBean.class);
                    if (gameevaluationbean.getEvaluationList() != null&&gameevaluationbean.getEvaluationList().size()>0) {
                        mAdapter.addMoreData(gameevaluationbean.getEvaluationList());
                        if (gameevaluationbean.getNext_key() == null) {
                            next_key = String.valueOf(gameevaluationbean.getEvaluationList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gameevaluationbean.getNext_key();
                        }
                        if (gameevaluationbean.getEvaluationList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    }
                    else {
                        Toast.makeText(getContext(), "没有更多数据啦", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    currentpage--;
                    Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取测评成功" + responseInfo.result);
                try {
                    gameevaluationbean = new Gson().fromJson(responseInfo.result, GameEvaluationBean.class);
                    if (gameevaluationbean.getEvaluationList() != null) {
                        mAdapter.addMoreData(gameevaluationbean.getEvaluationList());
                        if (gameevaluationbean.getNext_key() == null&&gameevaluationbean.getEvaluationList().size()>0) {
                            next_key = String.valueOf(gameevaluationbean.getEvaluationList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gameevaluationbean.getNext_key();
                        }
                        currentpage++;
                        acache.put("evaluation_game_load_more_" + currentpage, responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        if (gameevaluationbean.getEvaluationList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    } else {
                        Toast.makeText(getContext(), "没有更多数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }

    private void initHeadView() {
        //rListView.getRefreshableView().setAdapter(null);
        rListView.getRefreshableView().addHeaderView(getCustomHeaderView(getContext(), banner.getBannerList()));
        getFirstData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            Log.d("wei--", "GameEvaluation:" + isVisibleToUser);
            initIncar();
            if (banner == null) {
                getBanner();
            }
        }
    }

    public void initIncar() {
        MyApplication application = MyApplication.getMyApplication();
        isIncar = application.getIsInCar();
        mac = application.getMac();
    }


}